﻿from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.views import View
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from .models import Tag
import json


@method_decorator(login_required, name="dispatch")
class TagListView(View):
    template_name = "ip_analysis/tag_list.html"
    
    def get(self, request):
        name = request.GET.get("name", "")
        is_active = request.GET.get("is_active")
        page = request.GET.get("page", 1)
        per_page = request.GET.get("per_page", 20)
        
        queryset = Tag.objects.all()
        
        if name:
            queryset = queryset.filter(name__icontains=name)
        if is_active is not None:
            queryset = queryset.filter(is_active=is_active.lower() == "true")
        
        paginator = Paginator(queryset, per_page)
        tags = paginator.get_page(page)
        
        return render(request, self.template_name, {
            "tags": tags,
            "name": name,
            "is_active": is_active,
            "per_page": per_page
        })


@method_decorator(login_required, name="dispatch")
class TagCreateView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            name = data.get("name").strip()
            description = data.get("description", "").strip()
            
            if not name:
                return JsonResponse({"status": "error", "message": "标签名称不能为空"}, status=400)
            
            if len(name) > 50:
                return JsonResponse({"status": "error", "message": "标签名称长度不能超过50个字符"}, status=400)
            
            if Tag.objects.filter(name=name).exists():
                return JsonResponse({"status": "error", "message": "标签名称已存在"}, status=400)
            
            tag = Tag.objects.create(
                name=name,
                description=description,
                created_by=request.user
            )
            
            return JsonResponse({
                "status": "success", 
                "message": "标签创建成功",
                "tag": {
                    "id": tag.id,
                    "name": tag.name,
                    "description": tag.description,
                    "is_active": tag.is_active,
                    "created_at": tag.created_at.strftime("%Y-%m-%d %H:%M:%S")
                }
            })
        except json.JSONDecodeError:
            return JsonResponse({"status": "error", "message": "无效的请求数据"}, status=400)
        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)


@method_decorator(login_required, name="dispatch")
class TagUpdateView(View):
    def post(self, request, tag_id):
        tag = get_object_or_404(Tag, id=tag_id)
        
        try:
            data = json.loads(request.body)
            name = data.get("name").strip()
            description = data.get("description", "").strip()
            is_active = data.get("is_active", tag.is_active)
            
            if not name:
                return JsonResponse({"status": "error", "message": "标签名称不能为空"}, status=400)
            
            if len(name) > 50:
                return JsonResponse({"status": "error", "message": "标签名称长度不能超过50个字符"}, status=400)
            
            if Tag.objects.filter(name=name).exclude(id=tag_id).exists():
                return JsonResponse({"status": "error", "message": "标签名称已存在"}, status=400)
            
            tag.name = name
            tag.description = description
            tag.is_active = is_active
            tag.save()
            
            return JsonResponse({
                "status": "success", 
                "message": "标签更新成功",
                "tag": {
                    "id": tag.id,
                    "name": tag.name,
                    "description": tag.description,
                    "is_active": tag.is_active,
                    "updated_at": tag.updated_at.strftime("%Y-%m-%d %H:%M:%S")
                }
            })
        except json.JSONDecodeError:
            return JsonResponse({"status": "error", "message": "无效的请求数据"}, status=400)
        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)


@method_decorator(login_required, name="dispatch")
class TagDeleteView(View):
    def post(self, request, tag_id):
        tag = get_object_or_404(Tag, id=tag_id)
        
        try:
            tag.delete()
            return JsonResponse({"status": "success", "message": "标签删除成功"})
        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)


@method_decorator(login_required, name="dispatch")
class TagBatchActionView(View):
    def post(self, request):
        try:
            data = json.loads(request.body)
            tag_ids = data.get("tag_ids", [])
            action = data.get("action")
            
            if not tag_ids or not action:
                return JsonResponse({"status": "error", "message": "无效的请求参数"}, status=400)
            
            tags = Tag.objects.filter(id__in=tag_ids)
            
            if action == "delete":
                tags.delete()
                message = f"成功删除 {len(tag_ids)} 个标签"
            elif action == "activate":
                tags.update(is_active=True)
                message = f"成功启用 {len(tag_ids)} 个标签"
            elif action == "deactivate":
                tags.update(is_active=False)
                message = f"成功禁用 {len(tag_ids)} 个标签"
            else:
                return JsonResponse({"status": "error", "message": "未知的操作类型"}, status=400)
            
            return JsonResponse({"status": "success", "message": message})
        except json.JSONDecodeError:
            return JsonResponse({"status": "error", "message": "无效的请求数据"}, status=400)
        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)


def get_active_tags(request):
    tags = Tag.objects.filter(is_active=True).order_by("name")
    tag_list = [{"id": tag.id, "name": tag.name} for tag in tags]
    return JsonResponse({"tags": tag_list})
